//
//  ZDSureOrderControllerViewController.m
//  ZDPension
//
//  Created by 刘甲奇 on 2017/6/20.
//  Copyright © 2017年 maker. All rights reserved.
//

#import "ZDSureOrderController.h"
#import "ZDReceiverCell.h"
#import "ZDOrderGoodsCell.h"
#import "ZDPayTypeCell.h"
#import "MakerTools.h"
#import "ZDOldManModel.h"

#import "ZDNewAddressController.h"
#import "ZDAddressListController.h"

static NSString *const ZDReceiverCellId = @"ZDReceiverCell";
static NSString *const ZDOrderGoodsCellId = @"ZDOrderGoodsCell";
static NSString *const ZDPayTypeCellId = @"ZDPayTypeCell";

@interface ZDSureOrderController ()

/**
 <#Description#>
 */
@property(nonatomic, strong) UIButton *buyButton;
/**
 地址模型
 */
@property(nonatomic, strong) ZDAddressModel *addressModel;
/**
 payName
 */
@property(nonatomic, copy) NSString *payName;

@end

@implementation ZDSureOrderController

- (void)setupUI
{
    [super setupUI];
    
    self.title = @"确认订单";
    
    [self.view addSubview:self.buyButton];
    self.buyButton.frame = CGRectMake(10, LEScreenHeight -64 -60, LEScreenWidth-20, 50);
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDReceiverCell" bundle:nil] forCellReuseIdentifier:ZDReceiverCellId];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDOrderGoodsCell" bundle:nil] forCellReuseIdentifier:ZDOrderGoodsCellId];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDPayTypeCell" bundle:nil] forCellReuseIdentifier:ZDPayTypeCellId];
    self.tableView.sectionFooterHeight = 0.01;
    [self resetTablewFrame:CGRectMake(0, 0, LEScreenWidth, LEScreenHeight -64 -60)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectAddress:) name:SELECT_ADDRESS_NOTIFICATION object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newAddress:) name:NEW_ADDRESS_NOTIFICATION object:nil];
    
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)loadData
{
    self.payName = @"offline";
    
    [self requestAddressList];
    [self.dataSource addObjectsFromArray:self.buyGoods];
}
#pragma mark- 网络请求
- (void)requestAddressList
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [SVProgressHUD showWithStatus:@"正在加载中"];
    __weak typeof (self) weakSelf = self;
    [API requestPostAppendKey:AddressListUrl params:dict success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        ZDLog(@"%s---%d---%@",__func__,__LINE__,successCode);
        NSDictionary *datas = successCode[@"datas"];
        NSArray *address_list = datas[@"address_list"];
        if (address_list.count==0)
        {
            ZDAddressModel *model = [[ZDAddressModel alloc] init];
            model.noData = YES;
            
        }else
        {
            NSArray *tempModel = [ZDAddressModel mj_objectArrayWithKeyValuesArray:address_list];
            self.addressModel = tempModel[0];
        }
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
    } falure:^(NSError *er) {
        ZDLog(@"%s---%d---%@",__func__,__LINE__,er);
        [SVProgressHUD dismiss];
    }];
    
}

/**
 去购买
 */

- (void)requestBuy
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"" forKey:@"vat_hash"];
    ZDOldManModel *oldMan = [MakerTools readFromSandBox:OLDMAN_INFO];
    NSString *cardId = oldMan.idcard;
    
    NSMutableString *cartId = [NSMutableString string];
    if (self.buyTpye == ShopCarBuy)
    {
        for (int i = 0; i < self.dataSource.count; i++) {
            ZDShoppCarGoodsModel *model = self.dataSource[i];
            if (i == self.dataSource.count -1) {
                [cartId appendFormat:@"%@|1",model.cart_id];
            }else{
                [cartId appendFormat:@"%@|1,",model.cart_id];
            }
        }
  
    }else{
        [cartId appendFormat:@"%@|3",self.singalModel.goods_id];
    }
    
    if (self.buyTpye == ShopCarBuy) {
        [dict setObject:@"12|0" forKey:@"door_service"];
         [dict setObject:@"1" forKey:@"ifcart"];
    }else{
        [dict setObject:@"13|0" forKey:@"door_service"];

    }

    [dict setObject:cartId forKey:@"cart_id"];
    [dict setObject:@"0" forKey:@"pd_pay"];
    [dict setObject:@"" forKey:@"offpay_hash"];
    [dict setObject:cardId forKey:@"idcard"];
    [dict setObject:self.addressModel.address_id forKey:@"address_id"];
    [dict setObject:@"" forKey:@"invoice_id"];
    [dict setObject:self.payName forKey:@"pay_name"];
    

    [SVProgressHUD showWithStatus:@"正在加载中"];
    __weak typeof (self) weakSelf = self;
    [API requestPostAppendKey:PayMoneyUrl params:dict success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        ZDLog(@"%s---%d---%@",__func__,__LINE__,successCode);
        NSDictionary *datas = successCode[@"datas"];
        NSString *error = datas[@"error"];
        if (error)
        {
            [SVProgressHUD showInfoWithStatus:@"支付失败"];
        }else
        {
            [SVProgressHUD showInfoWithStatus:@"支付成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:PAY_SUCCESS_NOTIFICATION object:nil];
        }
        
    } falure:^(NSError *er) {
        ZDLog(@"%s---%d---%@",__func__,__LINE__,er);
        [SVProgressHUD dismiss];
    }];
}

#pragma mark- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1)
    {
        if (self.buyTpye == ShopCarBuy) {
            return self.dataSource.count;
        }else{
            return 1;
        }
        
    }else{
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ZDReceiverCell *cell = [tableView dequeueReusableCellWithIdentifier:ZDReceiverCellId forIndexPath:indexPath];
        
        cell.model = self.addressModel;

         __weak typeof (self) weakSelf = self;
        [cell addressChangeClick:^(NSInteger tag) {
            
            ZDAddressListController *addressList = [[ZDAddressListController alloc] init];
            addressList.mode = SelectAddress;
            [weakSelf.navigationController pushViewController:addressList animated:YES];
        }];
        return cell;
    }
    if (indexPath.section == 1) {
           ZDOrderGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:ZDOrderGoodsCellId forIndexPath:indexPath];
        if (self.buyTpye == ShopCarBuy) {
            cell.model = self.dataSource[indexPath.row];
        }else{
            cell.goodsDetailModel = self.singalModel;
        }
        
        return cell;
    }else{
        
        ZDPayTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:ZDPayTypeCellId forIndexPath:indexPath];
        cell.totalPriceLabel.text = self.totalPrice;
         __weak typeof (self) weakSelf = self;
        [cell payClick:^(NSInteger tag) {
            ZDLog(@"%s---%d---%ld",__func__,__LINE__,tag);
            if (tag == 1) {
                weakSelf.payName = @"offline";
            }else
            {
                weakSelf.payName = @"online";
            }
            
        }];
        
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (self.addressModel == nil)
        {
            //新建地址
            ZDNewAddressController *newAddress = [[ZDNewAddressController alloc] init];
            [self.navigationController pushViewController:newAddress animated:YES];
        }
    }
}
#pragma mark- 点击事件

/**
 确定购买
 */
- (void)gotoBuy
{
    ZDLog(@"%s---%d---去购买",__func__,__LINE__);
    [self requestBuy];
}

/**
 选择地址监听

 @param notification <#notification description#>
 */
- (void)selectAddress:(NSNotification *)notification
{
    self.addressModel = notification.object;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
- (void)newAddress:(NSNotification *)notification
{
    [self requestAddressList];
}
#pragma mark- getter
- (UIButton *)buyButton
{
    if (_buyButton == nil) {
        _buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buyButton setTitle:@"确认购买" forState:0];
        [_buyButton setTitleColor:[UIColor whiteColor] forState:0];
        [_buyButton setBackgroundColor:LEHaxColor(0xff6606)];
        [_buyButton.layer setCornerRadius:5];
        [_buyButton addTarget:self action:@selector(gotoBuy) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buyButton;
}
@end
